<template>
  <div class="content-box">
    <div ref="searchBox" class="search-box flex" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="100px"
      >
      <el-form-item label="公司集合" prop="companyIds">
        <el-select
          v-model="queryParams.companyIds"
          multiple
          collapse-tags
          clearable
          filterable
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
          @change="companyIdsChange"
        >
          <el-option
            v-for="(item, index) in companyIdOptionList"
            :key="index"
            :label="item.companyName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品集合" prop="productIds">
        <el-select
          v-model="queryParams.productIds"
          multiple
          collapse-tags
          clearable
          filterable
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
        >
          <el-option
            v-for="(item, index) in productIdOptionList"
            :key="index"
            :label="item.productName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="跟进状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          clearable
          filterable
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
        >
          <el-option
            v-for="(item, index) in orderStatusOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            plain
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="table-box">
      <el-row :gutter="10" class="mb8">
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="handleQuery"
          :columns="columnsList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-sticky-header
        ref="table"
        v-loading="loading"
        :data="dataList"
        :row-class-name="tableRowClassName"
      >
        <template v-for="(item,index) in columns.slice(0, columns.length - 1)">
          <el-table-column
            :key="index"
            :label="item.label"
            :prop="item.prop"
            :width="getColumnWidth(index)"
            :fixed="item.fixed"
            :sortable="item.sortable ? item.sortable : false"
            :show-overflow-tooltip="item.showTooltip"
            v-if="item.visible"
            align="center"
          >
             <template slot-scope="scope">
                <!-- 分配模式单独处理 -->
                <div v-if="item.prop == 'shareType'">
                    <el-popconfirm
                      :title="`确定重新${
                        !scope.row[item.prop] ? '抢单' : '派单'
                      }吗？`"
                      @confirm="changeShareType(scope.row)"
                    >
                      <el-button
                        slot="reference"
                        size="mini"
                        :style="{
                          color:'#fff',
                          backgroundColor: scope.row[item.prop]?'#fa8c16':'#5AA4AE',
                          borderColor: scope.row[item.prop]?'#fa8c16':'#5AA4AE',
                        }"
                        >{{ scope.row[item.prop] ? "抢单" : "派单" }}</el-button
                      >
                    </el-popconfirm>
                </div>
                <!-- 跟进状态单独处理 -->
                <div v-else-if="item.prop == 'orderStatus'">
                    <el-tag 
                     :type="orderStatusColor(scope.row[item.prop])" 
                     >
                     {{ ArrayFormatObj(orderStatusOptions)[scope.row[item.prop]]}}
                    </el-tag>
                </div>
                <!-- 重新分配状态单独处理 -->
                <div v-else-if="item.prop == 'isShare'" @click="showIsSharePopo(scope.row)">
                      <el-popover
                       placement="top"
                       title="重新分配状态操作"
                       :value ="isShareIndex === scope.row.id"
                       trigger="click"
                       >
                       <el-form style="width: 240px;" :model="isShareParams" :rules="isShareRules" :ref="`user_${scope.row.id}`">
                          <el-form-item 
                           label="跟进人" prop="userId" >
                             <el-select
                               v-model="isShareParams.userId"
                               clearable
                               filterable
                               placeholder="请选择"
                               style="width: 100%"
                             >
                               <el-option
                                 v-for="(item, index) in followUserList"
                                 :key="index"
                                 :label="item.followUser"
                                 :value="item.userId"
                               ></el-option>
                             </el-select>
                           </el-form-item>

                         <el-form-item
                            style="display: flex;justify-content: center;margin-bottom: 0;"
                            >
                           <el-button 
                           :disabled="followUserList && followUserList.length == 0"
                           type="primary" @click="clickSubmitIsShare(scope.row,`user_${scope.row.id}`)">提交</el-button>
                           <el-button @click="clickCancelIsShare(scope.row)">取消</el-button>
                         </el-form-item>
                       </el-form>
                       <el-button 
                          slot="reference"
                          size="mini" 
                          :style="{
                           color:'#fff',
                           backgroundColor: scope.row[item.prop]?'#EF845D':'#bb5100',
                           borderColor: scope.row[item.prop]?'#EF845D':'#bb5100'
                         }"
                         :disabled="!scope.row[item.prop]"
                        >{{ ArrayFormatObj(isShareOptions)[scope.row[item.prop]]}}</el-button>
                       </el-popover> 
                </div>
                <!-- 客户星级单独处理 -->
                <div v-else-if="item.prop == 'userLevel'">
                    {{ ArrayFormatObj(userLevelOption)[scope.row[item.prop]]}}
                </div>
                <span v-else>
                  {{  scope.row[item.prop]  }}
                </span>
             </template>
          </el-table-column>
        </template>
          <el-table-column
            fixed="right"
            :prop="columns[columns.length - 1].prop"
            :label="columns[columns.length - 1].label"
            align="center"
            :width="getColumnWidth(columns.length - 1)"
            v-if="columns[columns.length - 1].visible"
          >
            <template slot-scope="scope">
             <div :class="['flex-center',device === 'mobile'?'flex':'']">
              <el-button
                type="text"
                @click="openDetail(scope.row)"
                >详情
              </el-button>
             
             
             </div>
            </template>
        </el-table-column>
      </el-table>
      <!-- 使用分页插件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[10, 50, 100, 200, 500]"
        :page.sync="queryParams.pageIndex"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import tableStickyMixins from "@/mixins/tableStickyMixins";
import { mapGetters } from "vuex";

import {
  queryCrmCompanyList,
  queryCrmProductList
} from "@/api/sysCrm/crmCompany";
import {
  queryCrmCompanyByPage,
  getFollowUser,
  setFollowUser,
} from "@/api/sysCrm/crmCustomer";
export default {
  // 定义名字用于标识该组件是否被keep-alive缓存
  name: "CrmCustomer",
  data() {
    return {
      // 数据列表
      dataList: [],
      // 公司集合筛选项
      companyIdOptionList: [],
      // 产品筛选列表
      productIdOptionList: [],
      // 跟进状态筛选列表
      orderStatusOptions:[
        { label: "待跟进", value: 0 },
        { label: "跟进中", value: 1 },
        { label: "挂起", value: 2 },
        { label: "结束", value: 3 },
        { label: "转移", value: 4 },
      ],
      // 客户星级模式筛选项
      userLevelOption: [
        { label: "未打星级",value: -1, },
        { label: "0星",value: 0, },
        { label: "1星",value: 1, },
        { label: "2星",value: 2, },
        { label: "3星",value: 3, },
        { label: "4星",value: 4, },
        { label: "5星",value: 5, },
      ],
      // 重新分配状态筛选项
      isShareOptions: [
        { label: "不可分配", value: 0 },
        { label: "可分配", value: 1 },
      ],
      
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
      },
      loading: false,
      // 表格列信息（用于控制显示与隐藏)
      columnsList:[],
      // 显示搜索栏
      showSearch: true,


      // 重新分配状态当前激活项行数据
      isShareIndex:null,
      // 重新分配状态参数
      isShareParams: {},
      // 重新分配状态弹框表单校验规则
      isShareRules:{
        
      },
      // 可分配根进人列表
      followUserList:[],
    };
  },
  mixins: [tableStickyMixins],
  watch: {
    columns: {
      handler() {
        // 清空popover激活项索引
        this.isShareIndex = null;
        this.updateTableHeight();
      },
      deep: true,
    },
    dataList:{
      handler() {
        // 清空popover激活项索引
        this.isShareIndex = null
      },
      deep: true,
    },
  },
  created() {
    this.getProductIdList()
    this.getCompanyIdList()
    this.getList();
  },
  computed: {
    ...mapGetters(["sidebar", "device"]),
    // 计算当前列元素在所处环境的宽度
    getColumnWidth() {
      return (index) => {
        return this.isMobile
          ? this.columns[index].mobileWidth
          : this?.sidebar?.opened
          ? this.columns[index].pcWidth - this.slightWidth
          : this.columns[index].pcWidth + 17;
      };
    },
    // 将数组转换为对象形式
    ArrayFormatObj:()=>{
       return (arr)=>{
         return arr.reduce((pre, cur)=>{
           pre[cur.value] = cur.label;
           return pre;
         },{})
       }
    },
    // 跟进状态标签颜色处理
    orderStatusColor:()=>{
        return (state)=>{
           switch(state){
             case 0:
                return 'warning';
             case 1:
                return 'success';
             case 2:
                return 'danger';
             case 3:
                return 'null';
             case 4:
                return 'info';
             default:
           }
        }
    },
    // 表格列信息
    columns(){
      const arr = [
       {label: `公司简称`,prop: "companyName",visible: true,pcWidth: 180,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `客户姓名`,prop: "cusName",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `跟进状态`,prop: "orderStatus",visible: true,pcWidth: 120,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `跟进人`,prop: "followUser",visible: true,pcWidth: 120,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `重新分配`,prop: "isShare",visible: true,pcWidth: 120,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `手机号MD5`,prop: "phoneMd5",visible: true,pcWidth: 280,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `客户星级`,prop: "userLevel",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `省份`,prop: "provinceName",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `城市`,prop: "cityName",visible: true,pcWidth: 150,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `分配时间`,prop: "createTime",visible: true,pcWidth: 180,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `操作`,prop: "operation",visible: true,pcWidth: 120,mobileWidth: 80,fixed: "right",showTooltip: true},
      ]
      this.$set(this,'columnsList',arr)
      return arr
    }
  },
  methods: {
    // 公司筛选条件改变
    companyIdsChange(){
       this.getProductIdList()
    },
    // 获取公司筛选项列表
    getCompanyIdList(){
      queryCrmCompanyList().then(res=>{
        this.companyIdOptionList = res.data
      })
    },
    // 获取产品筛选列表
    getProductIdList(){
      queryCrmProductList({
        companyIds: this?.queryParams?.companyIds
      }).then(res=>{
        this.productIdOptionList = res.data
      })
    },
    // 分配模式切换触发回调
    changeShareType(row) {
      const params = {
        id: row?.id,
        shareType: row?.shareType ? 0 : 1,
      };
      setShareType(params).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.getList();
        }
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.$set(this.queryParams, "pageIndex", 1);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 完全重置到初始状态
      this.$set(this, "queryParams", {
        pageIndex: 1,
        pageSize: 10,
      });
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      queryCrmCompanyByPage(this.queryParams).then((response) => {
        // 处理数据
        this.dataList = response?.data?.list
        this.total = response?.data?.total;
        this.loading = false;
      }).catch((err) => {
        setTimeout(() => {// 延迟2s后自动取消
          this.loading = false;
        }, 2000);
      })
    },
    // 重置属性转化为新对象
    prefixKeys(obj, prefix) {
         return Object.keys(obj).reduce((acc, key) => {
           acc[prefix + key] = obj[key];
           return acc;
         }, {});
    },
    // 修改表格高度触发回调
    updateTableHeight() {
      this.$nextTick(() => {
        this.$refs.table.doLayout();
      });
    },
    openDetail(row){
      // 点击打开详情页面
      this.$router.push({
            path:'/sysCrm/crmCustomerDetail',
            query:{
              id:row?.id,
            }
      })
    },


    // 显示重新分配状态弹出窗回调
    showIsSharePopo(row) {
      if(!row?.isShare) return
      // 设置重新分配状态状态
      this.$set(this,'isShareParams',{
        id: row?.id,
      })
      // 获取重新分配信息数据
      getFollowUser(row?.id).then(res => { 
        if(res?.code == 200){ 
          // 设置跟进人列表
          this.$set(this,'followUserList',res?.data)
        }
      })
      // 设置索引打开弹窗
      this.isShareIndex = row?.id
    },
    // 点击取消重新分配状态
    clickCancelIsShare(row){
      this.$message.info("取消操作");
      this.isShareIndex = null;
    },
    // 点击提交重新分配状态
    clickSubmitIsShare(row,formName){
      this.$refs[formName][0].validate((valid) => {
        if (valid) {
          let params={};
          params = JSON.parse(JSON.stringify(this.isShareParams))
          // 设置主键id
          params.id = row.id;

          setFollowUser(params).then((res) => {
            if(res.code === 200){
              this.$message.success("操作成功");
              this.getList();
              this.isShareIndex = null;
            }
          });

        }
      })
    },
    // table行变色处理
    tableRowClassName({row, rowIndex}) {
       switch(row?.orderStatus){
          case 0:
            return 'yellow-row';
          case 1:
            return 'green-row';
          case 2:
            return 'red-row';
          case 3:
            return 'blue-row';
          case 4:
            return 'grey-row';
          default:
            return '';
       }
    },
    
  },
};
</script>

<style scoped lang="scss">
.title {
  font-size: 20px;
  color: #333333;
  font-weight: 500;
}
.search-box {
  margin: 0 0 20px;
  padding: 20px 20px 0;
  background: #fff;
  align-items: flex-start;
  border-radius: 6px;
}
.search-area {
  position: absolute;
  right: 20px;
}
.el-form-item__content {
  flex: 1;
  line-height: 40px;
  position: relative;
  font-size: 14px;
  min-width: 0;
}
::v-deep .el-dialog__body {
  border-top: 1px solid #dfe6ec;
  border-bottom: 1px solid #dfe6ec;
}
.el-table {
  // 滚动条加粗
  --scrollbar-height: 9px;
}

// 黄色行
::v-deep .el-table .yellow-row {
    background: rgb(253, 248, 237);
}
// 绿色行
::v-deep .el-table .green-row {
    background: #f0f9eb;
}
// 红色行
::v-deep .el-table .red-row {
    background: #f9ebeb;
}
// 蓝色行
::v-deep .el-table .blue-row {
    background: #bfdef5;
}
// 灰色行
::v-deep .el-table .grey-row {
    background: #e5ecf0;
}
</style>
